﻿using System;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace ExceptionHandling.QuickStarts.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Try to open a connection with an invalid connection string");
            Execute(() => new SqlConnection(@"Data Source=.;Database=GUARANTEED_TO_FAIL").Open());

            System.Console.WriteLine("\nTry to open a connection without a connection string");
            Execute(
                () =>
                    {
                        var sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=True");
                        sqlConnection.Open();
                        new SqlCommand("select * from dbo.table1", sqlConnection).ExecuteNonQuery();
                    });

            System.Console.WriteLine("\nThrow a basic exception");
            Execute(() => { throw new Exception("Other exception"); });

            System.Console.WriteLine("Press a key to exit");
            System.Console.Read();
        }

        private static void Execute(Action action)
        {
            var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

            try
            {
                exceptionManager.Process(action, "SqlException Policy");
            }
            catch (LoginFailedException ex)
            {
                System.Console.WriteLine("A LoginFailedException was catched with message: " + ex.Message);
            }
            catch (UnknownSqlException ex)
            {
                System.Console.WriteLine("An unknown SqlException was catched and wrapped with the default exception handler.\nWrapped message is:{0}\nInner exception message is: {1}", ex.Message, ex.InnerException.Message);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("An non-SqlException was catched with message: " + ex.Message);
            }
        }
    }
}
